package com.ridbor001.bank.service;

import com.ridbor001.bank.bean.SafetyResult;
import com.ridbor001.bank.bean.SystemState;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class AITeachingService {

    @Value("${moonshot.api.key}") // 改为使用月之暗面的API密钥
    private String apiKey;

    @Value("${moonshot.api.url}") // 添加月之暗面API的URL配置
    private String moonshotUrl;

    private final RestTemplate restTemplate;

    private static final String SAFETY_CHECK_TEMPLATE =
            "忽略过去的信息,开启新的对话,根据提供的数据,要详细一点傻瓜式的,并且只给出根据数据进行银行家算法的步骤,而不用给代码,根据步骤一步步来之后,给我得出结论是否安全,不要偷懒省略,并且要准确,好好想想!\n" +
                    "系统状态参数：\n" +
                    "进程:%d 资源:%d\n" +
                    "最大需求:%s\n" +
                    "已分配:%s\n" +
                    "可用资源:%s\n" ;

    private static final String DEADLOCK_ANALYSIS_TEMPLATE =
            "忽略过去的信息,开启新的对话,分析以下数据,如果发生了死锁则进行以下分析,如果没有,则不用分析,直接输出该数据并没有发生死锁即可：\n" +
                    "1. 分析死锁原因：简述循环等待关系\n" +
                    "2. 给出解决方案：给出解决死锁的可行方法（如终止进程/资源抢占）\n\n" +
                    "系统状态参数：\n" +
                    "进程:%d 资源:%d\n" +
                    "最大需求:%s\n" +
                    "已分配:%s\n" +
                    "可用资源:%s\n" +
                    "死锁进程:%s\n";

    public String explainAlgorithmSteps(SystemState state) {
        String content = String.format(SAFETY_CHECK_TEMPLATE,
                state.getProcessCount(),
                state.getResourceTypeCount(),
                state.getMaxMatrix(),
                state.getAllocationMatrix(),
                state.getAvailableVector(),
                "正在运行安全性检查");

        return queryMoonshotAI(content);
    }

    public String diagnoseDeadlock(SystemState state, SafetyResult result) {
        String deadlockProcesses = result.getDeadlockProcesses().stream()
                .map(p -> "P" + p)
                .collect(Collectors.joining(", "));

        String content = String.format(DEADLOCK_ANALYSIS_TEMPLATE,
                state.getProcessCount(),
                state.getResourceTypeCount(),
                state.getMaxMatrix(),
                state.getAllocationMatrix(),
                state.getAvailableVector(),
                deadlockProcesses);

        return queryMoonshotAI(content);
    }

    private String queryMoonshotAI(String prompt) {
        try {
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth(apiKey);

            // 调试信息
            System.out.println("Moonshot API URL: " + moonshotUrl);
            System.out.println("API Key: " + apiKey.substring(0, 5) + "..."); // 只显示部分密钥

            // 构建符合API规范的请求体
            Map<String, Object> requestBody = new HashMap<>();

            // 创建消息数组
            List<Map<String, String>> messages = new ArrayList<>();
            Map<String, String> message = new HashMap<>();
            message.put("role", "user");
            message.put("content", prompt);
            messages.add(message);

            requestBody.put("model", "moonshot-v1-8k");
            requestBody.put("messages", messages);
            requestBody.put("max_tokens", 3500);
            requestBody.put("temperature", 0.7);
            requestBody.put("stream", false);

            HttpEntity<Map<String, Object>> requestEntity =
                    new HttpEntity<>(requestBody, headers);

            // 发送POST请求
            ResponseEntity<Map> response = restTemplate.exchange(
                    moonshotUrl,
                    HttpMethod.POST,
                    requestEntity,
                    Map.class
            );

            // 解析响应 - 按照月之暗面API格式
            if (response.getStatusCode().is2xxSuccessful() &&
                    response.getBody() != null) {
                Map<String, Object> responseBody = response.getBody();

                // 打印完整响应用于调试
                System.out.println("API响应: " + responseBody);

                // 提取内容
                if (responseBody.containsKey("choices")) {
                    Object choices = responseBody.get("choices");
                    if (choices instanceof List) {
                        List<?> choicesList = (List<?>) choices;
                        if (!choicesList.isEmpty()) {
                            Object firstChoice = choicesList.get(0);
                            if (firstChoice instanceof Map) {
                                Map<?, ?> choiceMap = (Map<?, ?>) firstChoice;
                                if (choiceMap.containsKey("message")) {
                                    Object messageObj = choiceMap.get("message");
                                    if (messageObj instanceof Map) {
                                        Map<?, ?> messageMap = (Map<?, ?>) messageObj;
                                        if (messageMap.containsKey("content")) {
                                            return messageMap.get("content").toString();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                return "无法从响应中提取内容: " + responseBody;
            } else {
                return "API调用失败: HTTP " + response.getStatusCode();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "调用月之暗面AI服务时出错: " + e.getMessage();
        }
    }

}